#include "common.h"
#include "RtspServer.h"

// 全局变量定义
int server_initialized = 0;
mk_media g_media[MAX_CAMERAS] = {0};
StreamState g_stream_states[MAX_CAMERAS];

void start_zlmediakit_server_once() {
    if (server_initialized) return;

    char* ini_path = mk_util_get_exe_dir("config.ini");
    mk_config config = {
        .ini = ini_path,
        .ini_is_path = 1,
        .log_level = 0,
        .log_mask = LOG_CONSOLE,
        .log_file_path = NULL,
        .log_file_days = 0,
        .ssl = NULL,
        .ssl_is_path = 1,
        .ssl_pwd = NULL,
        .thread_num = 0
    };
    mk_env_init(&config);
    mk_free(ini_path);

    mk_http_server_start(80, 0);
    mk_rtsp_server_start(554, 0);
    mk_rtmp_server_start(1935, 0);
    mk_rtc_server_start(atoi(mk_get_option("rtc.port")));

    mk_events events = {
        .on_mk_media_changed = NULL,
        .on_mk_media_publish = NULL,
        .on_mk_media_play = NULL,
        .on_mk_media_not_found = NULL,
        .on_mk_media_no_reader = NULL,
        .on_mk_http_request = on_mk_http_request, //✅ 现在能识别了
        .on_mk_http_access = NULL,
        .on_mk_http_before_access = NULL,
        .on_mk_rtsp_get_realm = NULL,
        .on_mk_rtsp_auth = NULL,
        .on_mk_record_mp4 = NULL,
        .on_mk_shell_login = NULL,
        .on_mk_flow_report = NULL
    };
    mk_events_listen(&events);

    server_initialized = 1;
    printf("✅ ZLMediaKit server started on ports 80/554/1935\n");
}

mk_media create_stream(const char* stream_id) {
    if (!server_initialized) {
        fprintf(stderr, "Error: ZLMediaKit server not initialized!\n");
        return NULL;
    }

    mk_media media = mk_media_create("__defaultVhost__", "live", stream_id, 0, 0, 0);
    if (media) {
        printf("✅ Stream created: live/%s\n", stream_id);
    } else {
        fprintf(stderr, "Failed to create stream: %s\n", stream_id);
    }
    return media;
}

void add_adts_header(uint8_t *data, int data_len, int sample_rate, int channels) {
    int profile = 2; // AAC LC
    int freqIdx;
    int chanCfg = channels;

    switch (sample_rate) {
        case 96000: freqIdx = 0; break;
        case 88200: freqIdx = 1; break;
        case 64000: freqIdx = 2; break;
        case 48000: freqIdx = 3; break;
        case 44100: freqIdx = 4; break;
        case 32000: freqIdx = 5; break;
        case 24000: freqIdx = 6; break;
        case 22050: freqIdx = 7; break;
        case 16000: freqIdx = 8; break;
        case 12000: freqIdx = 9; break;
        case 11025: freqIdx = 10; break;
        case 8000:  freqIdx = 11; break;
        default:
            fprintf(stderr, "Unsupported sample rate: %d\n", sample_rate);
            return;
    }

    data[0] = 0xFF;
    data[1] = 0xF1;
    data[2] = ((profile - 1) << 6) | (freqIdx << 2) | (chanCfg >> 2);
    data[3] = ((chanCfg & 3) << 6) | (data_len >> 11);
    data[4] = (data_len & 0x7FF) >> 3;
    data[5] = ((data_len & 7) << 5) | 0x1F;
    data[6] = 0xFC;
}
